/* eslint-disable */
import axios from 'axios'
import Cookies from 'js-cookie'
import { MessageBox } from 'element-ui'
import { getGlobalData } from '@/utils/global_data'

const isProd = process.env.NODE_ENV === 'production'

export function createServerHttp (cookies, xForwardedFor) {

  const baseURL = isProd ? 'http://fuwu.jtyedu.com' : 'http://192.168.2.240:9003'

  const headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
  }

  if (xForwardedFor) headers['x-forwarded-for'] = xForwardedFor

  // 使用自定义配置 创建一个 axios 实例
  const instance = axios.create({
    baseURL: baseURL,
    timeout: 1000 * 20,
    headers
  })

  // 添加请求拦截器
  instance.interceptors.request.use(config => {
    if (cookies['user-token']) {
      let accessToken = JSON.parse(cookies['user-token']).access_token
      config.headers.Authorization = 'Bearer ' + accessToken
    }
    return config
  })
  return instance
}


export function createClientHttp () {
  // 使用自定义配置 创建一个 axios 实例
  const instance = axios.create({
    baseURL: '/',
    timeout: 1000 * 20,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'X-Requested-With': 'XMLHttpRequest',
      'If-Modified-Since': 'Thu, 01 Jun 1970 00:00:00 GMT', // 避免 IE10 返回 304
      'shouldIntercept': true // 若为 false,则不拦截在自己的请求里处理
    }
  })

  // 添加请求拦截器
  instance.interceptors.request.use(config => {
    const userToken = Cookies.getJSON('user-token')
    if (!config.headers.Authorization && userToken) {
      config.headers.Authorization = 'Bearer ' + userToken.access_token
    }
    return config
  }, error => {
    return Promise.reject(error)
  })

  // 添加响应拦截器
  instance.interceptors.response.use(response => {
    return response
  }, error => {
    let router = getGlobalData('router')
    if (error.response && error.response.status === 401) {
      MessageBox.confirm('您当前还未登录, 是否先去登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        router.push({ name: 'login' })
      }).catch(() => {})
    } else if (error.response && error.response.data) {
      return Promise.reject(error.response.data)
    } else {
      return Promise.reject({ msg: '服务器开小差了，请稍后再试哦~' })
    }

    return Promise.reject(error)
  })

  return instance
}
